<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click="dialogVisible=true">
      上传
    </el-button>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <el-upload
        :multiple="true"
        :headers="headers"
        :accept="accept"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        class="editor-slide-upload"
        :action="baseUrl + action"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/token'
import * as auth from '@/utils/auth'
import { uuid } from '@/utils/utils'
const baseUrl = process.env.VUE_APP_BASE_API
const resUrl = process.env.VUE_APP_RES_URL

export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    action: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png,.gif,.bmp'
    },
    maxSize: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      baseUrl: baseUrl,
      resUrl: resUrl,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      dialogVisible: false,
      listObj: {},
      fileList: []
    }
  },
  mounted () {
    this.setHeaders()
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      const images = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message.warning('请等待所有图片上传完毕')
        return
      }
      this.$emit('successCBK', images)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = this.resUrl + response.data
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const filename = file.name
      const filesize = file.size
      const ext = filename.substring(filename.lastIndexOf('.'))
      if (this.accept.indexOf(ext) < 0) {
        this.$message.error('请上传' + this.accept + '格式的文件')
        return false
      }
      if (filesize > this.maxSize * 1024 * 1024) {
        this.$message.error('文件最大大小' + this.maxSize + 'MB')
        return false
      }
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        }
        resolve(true)
      })
    },
    setHeaders() {
      this.headers['App-Auth-appid'] = auth.APPID
      if (auth.APP_AUTH_ENABLE) {
        this.headers['App-Auth-reqUrl'] = this.action
        let timestamp = new Date().getTime()
        let nonceStr = uuid()
        this.headers['App-Auth-timestamp'] = timestamp
        this.headers['App-Auth-nonceStr'] = nonceStr
        this.headers['App-Auth-sign'] = auth.generateSignQs(
          this.action,
          timestamp,
          nonceStr,
          {}
        )
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  ::v-deep .el-upload--picture-card {
    width: 100%;
  }
}
</style>
